/**
 * Created by Administrator on 2016/1/26.
 */
;(function(window, document, undefined) {

    var modalClass   = '.da_toast',
        alertTypes   = ['error', 'loading', 'success'],
        defaultParams = {
            text: '',
            type: null,
            timer: null,
            html: false
        };

    /*
     * Manipulate DOM
     */

    var getModal = function() {
        var $modal = document.querySelector(modalClass);

        if (!$modal) {
            sweetAlertInitialize();
            $modal = getModal();
        }

        return $modal;
    },
    hasClass = function(elem, className) {
        return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
    },
    addClass = function(elem, className) {
        if (!hasClass(elem, className)) {
            elem.className += ' ' + className;
        }
    },
    removeClass = function(elem, className) {
        var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, ' ') + ' ';
        if (hasClass(elem, className)) {
            while (newClass.indexOf(' ' + className + ' ') >= 0) {
                newClass = newClass.replace(' ' + className + ' ', ' ');
            }
            elem.className = newClass.replace(/^\s+|\s+$/g, '');
        }
    },
    escapeHtml = function(str) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    },
    _show = function(elem) {
        elem.style.display = 'block';
    },
    show = function(elems) {
        if (elems && !elems.length) {
            return _show(elems);
        }
        for (var i = 0; i < elems.length; ++i) {
            _show(elems[i]);
        }
    },
    _hide = function(elem) {
        elem.style.display = 'none';
    },
    hide = function(elems) {
        if (elems && !elems.length) {
            return _hide(elems);
        }
        for (var i = 0; i < elems.length; ++i) {
            _hide(elems[i]);
        }
    };

    /*
     * Add modal + overlay to DOM
     */

    var sweetAlertInitialize = function() {
        var sweetHTML = '<div class="da_toast">'+
                '<div class="da_body da_error"><i class="iconfont icon-iconsb"></i></div>'+
                '<div class="da_body da_loading"><div class="da_animate"><div class="da_loading_leaf da_loading_leaf_0"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_1"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_2"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_3"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_4"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_5"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_6"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_7"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_8"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_9"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_10"></div>'+
                '<div class="da_loading_leaf da_loading_leaf_11"></div></div></div>'+
                '<div class="da_body da_success"><i class="iconfont icon-iconchenggong"></i></div>'+
                '<p class="da_toast_content"></p>'+
                '</div>',
            sweetWrap = document.createElement('div');

        sweetWrap.innerHTML = sweetHTML;

        // Append elements to body
        while (sweetWrap.firstChild) {
            document.body.appendChild(sweetWrap.firstChild);
        }
    };


    /*
     * Global sweetAlert function
     */
    var sweetAlert, dfal;

    sweetAlert = dfal = function() {
        var customizations = arguments[0];

        /*
         * Use argument if defined or default value from params object otherwise.
         * Supports the case where a default value is boolean true and should be
         * overridden by a corresponding explicit argument which is boolean false.
         */
        function argumentOrDefault(key) {
            var args = customizations;

            if (typeof args[key] !== 'undefined') {
                return args[key];
            } else {
                return defaultParams[key];
            }
        }

        var params = extend({}, defaultParams);

        switch (typeof arguments[0]) {

            // Ex: dfal("Hello", "Just testing", "info");
            case 'string':
                params.text  = arguments[0] || '';
                params.type  = arguments[1] || '';

                break;

            // Ex: dfal({title:"Hello", text: "Just testing", type: "info"});
            case 'object':

                var availableCustoms = [
                    'text',
                    'type',
                    'timer',
                    'html'];

                // It would be nice to just use .forEach here, but IE8... :(
                var numCustoms = availableCustoms.length;
                for (var customIndex = 0; customIndex < numCustoms; customIndex++) {
                    var customName = availableCustoms[customIndex];
                    params[customName] = argumentOrDefault(customName);
                }

                break;

            default:
                return false;

        }
        setParameters(params);
        openModal();

        // Modal interactions
        var modal = getModal();
    };

    /*
     * Set type, text and actions on modal
     */

    function setParameters(params) {
        var modal = getModal();

        var $text = modal.querySelector('p');

        // Text
        $text.innerHTML = (params.html) ? params.text : escapeHtml(params.text || '').split("\n").join("<br>");

        // Close timer
        modal.setAttribute('data-timer', params.timer);

        // Icon
        hide(modal.querySelectorAll('.da_body'));
        if (params.type) {
            var validType = false;
            for (var i = 0; i < alertTypes.length; i++) {
                if (params.type === alertTypes[i]) {
                    validType = true;
                    break;
                }
            }
            if (!validType) {
                return false;
            }
            var $body = modal.querySelector('.da_body.' + 'da_' + params.type);
            show($body);
        }
    }

    /*
     * Set hover, active and focus-states for buttons (source: http://www.sitepoint.com/javascript-generate-lighter-darker-color)
     */

    function extend(a, b){
        for (var key in b) {
            if (b.hasOwnProperty(key)) {
                a[key] = b[key];
            }
        }
        return a;
    }

    //opening modal
    function openModal() {
        var modal = getModal();
        addClass(modal, 'showAlert');
        removeClass(modal, 'hideAlert');
        var timer = modal.getAttribute('data-timer');

        if (timer !== "null" && timer !== "") {
            modal.timeout = setTimeout(function() {
                sweetAlert.close();
            }, timer);
        }
    }

    //closing modal
    sweetAlert.close = dfal.close = function() {
        var modal = getModal();
        removeClass(modal, 'showAlert');
        addClass(modal, 'hideAlert');
    };

    if (typeof define === 'function' && define.amd) {
        define(function() { return sweetAlert; });
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = sweetAlert;
    } else if (typeof window !== 'undefined') {
        window.sweetAlert = window.dfal = sweetAlert;
    }

})(window, document);